<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use fast\Tree;
use Exception;
class Goods extends Model
{

    // 表名
    protected $name = 'kuyou_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        $map = [];
        foreach ($where as $where_k=>$where_v){
            $map['g.'.$where_k] = $where_v;
        }
        if($pageStatus){
            $list = Db::name('kuyou_goods')->alias('g')
                ->join('kuyou_unit u','g.unit_id=u.id')
                ->where($map)
                ->page($page,$limit)
                ->field('g.id,g.goods_code,g.goods_type_id,g.goods_name,g.goods_barcode,g.note,g.goods_specification_id as goods_spec,g.unit_id,u.name as unit_name,g.more_unit
                ,g.market_sell_price,g.wholesale_price,g.vip_price,g.purchase,g.goods_image,g.inventory as stock,g.is_offten,g.status,FROM_UNIXTIME(g.updatetime,\'%Y-%m-%d %H:%i:%s\') as updatetime')
                ->order(['g.createtime'=>'DESC','g.goods_code'=>'DESC'])
                ->select();
        }else{
            $list = Db::name('kuyou_goods')->alias('g')
                ->join('kuyou_unit u','g.unit_id=u.id')
                ->where($map)
                ->field('g.id,g.goods_code,g.goods_type_id,g.goods_name,g.goods_barcode,g.note,g.goods_specification_id as goods_spec,g.unit_id,u.name as unit_name,g.more_unit
                ,g.market_sell_price,g.wholesale_price,g.vip_price,g.purchase,g.goods_image,g.inventory as stock,g.is_offten,g.status,FROM_UNIXTIME(g.updatetime,\'%Y-%m-%d %H:%i:%s\') as updatetime')
                ->order(['g.createtime'=>'DESC','g.goods_code'=>'DESC'])
                ->select();
        }
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['type_name'] = (new GoodsType())->where(['id'=>$list_v['goods_type_id']])->value('supplier_type_name');
            $unit = (new Unit())->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
            if($unit){
                $unit_name = $unit['name'];
                $rowadvance_rate = '1';
                if($list_v['more_unit']==1){
                    $more_unit = Db::name('kuyou_unit_conversion')->alias('uc')
                        ->join('kuyou_unit u','u.id=uc.vice_unit')
                        ->where(['uc.main_unit'=>$unit['id']])
                        ->order('uc.advance_rate','ASC')
                        ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                        ->select();
                    foreach ($more_unit as $unit_k=>$unit_v){
                        $unit_name .= ','.$unit_v['name'];
                        $rowadvance_rate .= ':'.$unit_v['advance_rate'];
                    }
                    $list[$list_k]['unit_name'] = $unit_name.'('.$rowadvance_rate.')';
                }
            }
        }
        $count = Db::name('kuyou_goods')->alias('g')
            ->join('kuyou_unit u','g.unit_id=u.id')
            ->where($map)
            ->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id,$type){
        $model = new Goods();
        $row = $model->where(['id'=>$id])
            ->field('id,goods_code,goods_name,goods_barcode,goods_specification_id as goods_spec,goods_type_id,manager_warehouse_id,unit_id,is_offten,status,
            unit_id,goods_image,goods_images,note,serial,
            more_unit,stock_warning,branch,auxiliary,batch,serial,period_status,warehousing,warehouse')
            ->find();
        if(empty($row)){
            return ['status'=>500,'msg'=>'未查询到数据'];
        }else{

            $row['goods_type_name'] = (new GoodsType())->where(['id'=>$row['goods_type_id']])->value('supplier_type_name');
            $row['manager_warehouse_name'] = (new Stores())->where(['id'=>$row['manager_warehouse_id']])->value('name');
            $row['warehousing_name'] = (new Unit())->where(['id'=>$row['warehousing']])->value('name');
            $row['warehouse_name'] = (new Unit())->where(['id'=>$row['warehouse']])->value('name');
            $row['unit_name'] = (new Unit())->where(['id'=>$row['unit_id']])->value('name');

            if(!empty($row['goods_images'])){
                $row['goods_images'] = explode(',',$row['goods_images']);
            }

            if($type==1){
                $row['price_data'] = self::getGoodsPrice($row['id']);//商品价格策略

                $row['more_unit_data'] = [];//商品多单位信息与单位价格信息
                if($row['more_unit']==1){//商品开启多单位
                    $row['more_unit_data'] = self::getGoodsUnit($row['id']);
                }

                $row['stock_waring_data'] = [];//商品库存预警信息
                if($row['stock_warning']==1){//商品开启库存预警
                    $row['stock_waring_data'] = self::getGoodsWaring($row['id']);
                }

                $row['auxiliary_data'] = [];//商品属性信息
                if($row['auxiliary']==1){//商品开启属性
                    $row['auxiliary_data'] = self::getGoodsAuxiliary($row['id']);
                }

                $row['batch_data'] = [];//商品批次保质期信息
                if($row['batch']==1){//商品开启批次保质期
                    $row['batch_data'] = self::getGoodsBatch($row['id']);
                }

                $row['period_data'] = [];//商品期初信息
                if($row['period_status']==1){//商品开启期初
                    $row['period_data'] = self::getGoodsPeriod($row['id']);
                }
            }
        }
        return ['status'=>200,'msg'=>$row];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'goods_code|编号'=>'require',
                'goods_name|名称'=>'require',
                'goods_type_id|商品分类'=>'require',
                'status|状态'=>'require|in:0,1',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['goods_code'],6);//验证编号是否合法
                if($status){
                    $detail['more_unit'] = isset($detail['more_unit'])?$detail['more_unit']:0;
                    $detail['stock_warning'] = isset($detail['stock_warning'])?$detail['stock_warning']:0;
                    $detail['batch'] = isset($detail['batch'])?$detail['batch']:0;
                    $detail['serial'] = isset($detail['serial'])?$detail['serial']:0;
                    $model = new Goods();
                    $goods = $model->where(['goods_code'=>trim($detail['goods_code'])])->value('id');
                    if($goods){
                        return ['status'=>500,'msg'=>'商品编号已使用'];
                    }

                    if(isset($detail['goods_barcode']) && !empty($detail['goods_barcode'])){//商品条码
                        $barcode = \think\Db::name('kuyou_goods')->where(['goods_barcode'=>$detail['goods_barcode']])->value('id');
                        if($barcode){
                            return ['status'=>500,'msg'=>'商品条码已被使用'];
                        }
                    }

                    if(isset($detail['goods_type_id']) && !empty($detail['goods_type_id'])){//选择了商品分类
                        $goods_type_id = $detail['goods_type_id'];
                        $goods_type = (new GoodsType())->where(['id'=>$goods_type_id])->value('id');
                        if(empty($goods_type)){
                            return ['status'=>500,'msg'=>'商品分类不存在'];
                        }
                    }

                    if(isset($detail['manager_warehouse_id']) && !empty($detail['manager_warehouse_id'])){//选择了商品默认仓库
                        $id = $detail['manager_warehouse_id'];
                        $stores = (new Stores())->where(['id'=>$id])->value('id');
                        if(empty($stores)){
                            return ['status'=>500,'msg'=>'首选仓库不存在'];
                        }
                    }

                    $more_unit = isset($detail['more_unit'])?$detail['more_unit']:2;
                    $more_unit = empty($more_unit)?2:$more_unit;
                    $goods_price = [];//多单位&价格设置
                    if($more_unit==2){//单计量单位
                        if(isset($detail['unit_id']) && !empty($detail['unit_id'])){//选择了商品单位
                            $id = $detail['unit_id'];
                            $unit = (new Unit())->where(['id'=>$id])->value('id');
                            if(empty($unit)){
                                return ['status'=>500,'msg'=>'商品单位不存在'];
                            }
                        }
                        if(!isset($detail['price_data']) || (isset($detail['price_data']) && empty($detail['price_data']))){
                            return ['status'=>500,'msg'=>'请设置商品价格策略'];
                        }else{
                            if(!is_array($detail['price_data'])){
                                $price_data = (array)json_decode(html_entity_decode($detail['price_data']), true);
                                $price_data = isset($price_data[0])?$price_data[0]:$price_data;
                            }else{
                                $price_data = $detail['price_data'];
                            }
                            $check = (new Commons())->checkParameter($price_data,[
                                'market_sell_price|零售价'=>'require|money',
                                'wholesale_price|批发价'=>'require|money',
                                'vip_price|VIP会员价'=>'require|money',
                                'discount|折扣率1'=>'require|money',
                                'discount2|折扣率2'=>'require|money',
                                'purchase|预计采购价'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }else{
                                $detail['market_sell_price'] = $price_data['market_sell_price'];
                                $detail['wholesale_price'] = $price_data['wholesale_price'];
                                $detail['vip_price'] = $price_data['vip_price'];
                                $detail['discount'] = $price_data['discount'];
                                $detail['discount2'] = $price_data['discount2'];
                                $detail['purchase'] = $price_data['purchase'];
                            }
                        }
                    }else{//多计量单位
                        if(!isset($detail['more_unit_id']) || (isset($detail['more_unit_id']) && empty($detail['more_unit_id']))){
                            return ['status'=>500,'msg'=>'请选择商品多单位'];
                        }else{
                            $id = $detail['more_unit_id'];
                            $detail['unit_id'] = $id;
                            $arr = [];

                            $unit_id = [];
                            $unit = (new Unit())->where(['id'=>$id])->value('id');
                            if(empty($unit)){
                                return ['status'=>500,'msg'=>'商品单位不存在'];
                            }
                            $arr[] = ['id'=>$unit,'advance_rate'=>1];$unit_id[] = $unit;

                            $unit_data = collection((new UnitConversions())
                                ->where(['main_unit'=>$id])
                                ->order('advance_rate','ASC')
                                ->field('vice_unit as id,advance_rate')->select())->toArray();
                            if(empty($unit_data)){
                                return ['status'=>500,'msg'=>'商品多单位不存在'];
                            }
                            foreach ($unit_data as $unit_k=>$unit_v){
                                $arr[] = $unit_v;$unit_id[] = $unit_v['id'];
                            }
                            if(!is_array($detail['more_unit_data'])){
                                $data = (array)json_decode(html_entity_decode($detail['more_unit_data']), true);
                            }else{
                                $data = $detail['more_unit_data'];
                            }
                            foreach ($data as $data_k=>$data_v){
                                $check = (new Commons())->checkParameter($data_v,[
                                    'unit|多单位'=>'require|number',
                                    'market_sell_price|零售价'=>'require|money',
                                    'wholesale_price|批发价'=>'require|money',
                                    'vip_price|VIP会员价'=>'require|money',
                                    'discount|折扣率1'=>'require|money',
                                    'discount2|折扣率2'=>'require|money',
                                    'purchase|预计采购价'=>'require|money',
                                ]);
                                if(isset($check['status'])){
                                    return $check;
                                }
                                if(!in_array($data_v['unit'],$unit_id)){
                                    return ['status'=>500,'msg'=>'商品多单位设置错误'];
                                }
                                $goods_price[] = [
                                    'goods_code'=>$detail['goods_code'],
                                    'goods_name'=>$detail['goods_name'],
                                    'goods_barcode'=>$detail['goods_barcode'],
                                    'unit'=>$data_v['unit'],
                                    'market_sell_price'=>$data_v['market_sell_price'],
                                    'wholesale_price'=>$data_v['wholesale_price'],
                                    'vip_price'=>$data_v['vip_price'],
                                    'discount'=>$data_v['discount'],
                                    'discount2'=>$data_v['discount2'],
                                    'purchase'=>$data_v['purchase'],
                                    'is_default'=>($data_v['unit']==$id?'1':'0'),
                                ];
                            }
                            $detail['market_sell_price'] = $data[0]['market_sell_price'];
                            $detail['wholesale_price'] = $data[0]['wholesale_price'];
                            $detail['vip_price'] = $data[0]['vip_price'];
                            $detail['discount'] = $data[0]['discount'];
                            $detail['discount2'] = $data[0]['discount2'];
                            $detail['purchase'] = $data[0]['purchase'];
                            $detail['unit_id'] = $data[0]['unit'];
                        }
                    }


                    $goods_stock_warning = [];//预警设置
                    if($detail['stock_warning']==1 && $detail['branch']==1){
                        if(!is_array($detail['stock_data'])){
                            $stock_data = (array)json_decode(html_entity_decode($detail['stock_data']), true);
                        }else{
                            $stock_data = $detail['stock_data'];
                        }
                        foreach ($stock_data as $k=>$v){
                            $check = (new Commons())->checkParameter($v,[
                                'stores_id|仓库'=>'require|number',
                                'min_stock|最小库存'=>'require|money',
                                'max_stock|最大库存'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }
                            $goods_stock_warning[] = [
                                'goods_id'    => '',
                                'goods_code'  => $detail['goods_code'],
                                'stores_id'=>$v['stores_id'],
                                'min_stock'=>$v['min_stock'],
                                'max_stock'=>$v['max_stock'],
                            ];
                        }
                    }

                    $combination = [];//属性组合记录
                    $combination_id = [];//属性组合ID
                    $auxiliary_id = [];//所有属性组合ID
                    $goods_attr = [];//属性价格
                    if($detail['auxiliary']==1 && self::getSet('auxiliary','is_checked')==1){
                        $auxiliary_type = explode(',',$detail['auxiliary_type']);
                        $arr = Db::name('kuyou_auxiliary')->where(['id'=>['in',$detail['auxiliary_type']]])->field('id,name')->select();
                        if(sizeof($arr)!=sizeof($auxiliary_type)){
                            return ['status'=>500,'msg'=>'一级属性选择错误'];
                        }
                        $auxiliary_type_c = explode(',',$detail['auxiliary_type_c']);
                        $arr = Db::name('kuyou_auxiliary')->where(['id'=>['in',$detail['auxiliary_type_c']]])->field('id,name')->select();
                        if(sizeof($arr)!=sizeof($auxiliary_type_c)){
                            return ['status'=>500,'msg'=>'二级属性选择错误'];
                        }
                        $detail['auxiliary_type'] = serialize($auxiliary_type);
                        $detail['auxiliary_type_c'] = serialize($auxiliary_type_c);
                        $auxiliary = self::auxiliary($auxiliary_type,$auxiliary_type_c);
                        foreach ($auxiliary as $auxiliary_k=>$auxiliary_v){
                            $auxiliary_v_id = explode('&',$auxiliary_v['id']);
                            sort($auxiliary_v_id);
                            $auxiliary_id[] = implode('&',$auxiliary_v_id);
                        }
                        if(!is_array($detail['auxiliary_data'])){
                            $auxiliary_data = (array)json_decode(html_entity_decode($detail['auxiliary_data']), true);
                        }else{
                            $auxiliary_data = $detail['auxiliary_data'];
                        }
                        foreach ($auxiliary_data as $k=>$v){
                            $auxiliary_v_id = explode('&',$v['attr_id']);
                            sort($auxiliary_v_id);
                            $v['attr_id'] = implode('&',$auxiliary_v_id);

                            if(!in_array($v['attr_id'],$auxiliary_id) || empty($v['attr_id'])){
                                return ['status'=>500,'msg'=>'属性价格设置错误'];
                            }else if(in_array($v['attr_code'],$combination_id) || empty($v['attr_code'])){
                                return ['status'=>500,'msg'=>'属性编号重复'];
                            }else{
                                $combination[] = [
                                    'attr_ids'  => $v['attr_id'],
                                    'attr_code' => $v['attr_code'],
                                ];
                                $combination_id[] = $v['attr_code'];
                                $v['goods_code'] = $detail['goods_code'];
                                $v['goods_name'] = $detail['goods_name'];
                                $v['goods_barcode'] = $detail['goods_barcode'];
                                $v['goods_code'] = $detail['goods_code'];
                                $v['unit'] = $detail['unit_id'];
                                $goods_attr[] = $v;
                            }
                        }
                        $status = Db::name('kuyou_goods_attr')->where(['attr_code'=>['in',$combination_id]])->find();
                        if($status){
                            return ['status'=>500,'msg'=>'商品属性编号已占用'];
                        }
                    }
                    if($detail['batch']==1 && $detail['serial']==1){
                        return ['status'=>500,'msg'=>'商品不能同时启用批次管理和序列号管理'];
                    }

                    //启用批次保质期管理
                    $goods_batch = [];
                    if($detail['batch']==1 && self::getSet('batch','is_checked')==1){
                        if (empty($detail['shelf_life'])){
                            return ['status'=>500,'msg'=>'请输入保质期天数'];
                        }
                        if (empty($detail['early_warning'])){
                            return ['status'=>500,'msg'=>'请输入预警天数'];
                        }
                    }

                    $goods_stock = [];//商品库存
                    $goods_stock_log = [];//库存记录

                    $detail['period_status'] = isset($detail['period_status'])?$detail['period_status']:0;
                    //启用商品序列号
                    $goods_serial = [];
                    $serial_log = [];
                    $serial_code = [];
                    $inventory = 0;//期初库存
                    $price = 0;//期初余额
                    if(!empty($detail['period_data']) && $detail['period_status']==1){
                        if(!is_array($detail['period_data'])){
                            $period_data = (array)json_decode(html_entity_decode($detail['period_data']), true);
                        }else{
                            $period_data = $detail['period_data'];
                        }
                        foreach ($period_data as $period_data_k=>$period_data_v){
                            $check = (new Commons())->checkParameter($period_data_v,[
                                'stores_id|仓库'=>'require|number',
                                'period|期初数量'=>'require|money',
                                'unit_cost|单位成本'=>'require|money',
                                'price|期初总价'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }

                            $auxiliary_v_id = explode('&',$period_data_v['attr_id']);
                            sort($auxiliary_v_id);
                            $period_data_v['attr_id'] = implode('&',$auxiliary_v_id);

                            if(!in_array($period_data_v['attr_id'],$auxiliary_id) && $detail['auxiliary']==1){
                                return ['status'=>500,'msg'=>'期初选择属性错误'];
                            }
                            if($detail['batch']==1 && self::getSet('batch','is_checked')==1){
                                $check = (new Commons())->checkParameter($period_data_v,[
                                    'batch_name|批次'=>'require',
                                    'manufacture|生产日期'=>'require',
                                    'validity|到期时间'=>'require',
                                ]);
                                if(isset($check['status'])){
                                    return $check;
                                }
                                $goods_batch[] = [
                                    'goods_id'    => '',
                                    'goods_code'  => $detail['goods_code'],
                                    'attribute_id'=> $period_data_v['attr_id'],
                                    'stores_id'   => $period_data_v['stores_id'],
                                    'stock'       => (float)$period_data_v['period'],
                                    'number'      => (float)$period_data_v['period'],
                                    'batch_name'  => $period_data_v['batch_name'],
                                    'manufacture' => $period_data_v['manufacture'],
                                    'guarantee'   => $detail['shelf_life'],
                                    'validity'    => $period_data_v['validity'],
                                    'type'        => 1,
                                    'address'     =>$period_data_v['address'],
                                    'registration'=>$period_data_v['registration'],
                                    'production'  =>$period_data_v['production'],
                                ];
                            }
                            //序列号
                            if($detail['serial']==1 && (isset($period_data_v['serial']) && empty($period_data_v['serial']) || !isset($period_data_v['serial']))  && getSet('serial','is_checked')==1){
                                return ['status'=>500,'msg'=>'请输入商品序列号'];
                            }
                            if($detail['serial']==1 && isset($period_data_v['serial']) && !empty($period_data_v['serial']) && self::getSet('serial','is_checked')==1){
                                $period_period = $period_data_v['serial'];
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $status = Db::name('kuyou_goods_serial')->where(['serial'=>$period_period_v['serial']])->find();
                                    if($status){
                                        return ['status'=>500,'msg'=>'商品序列号'.$period_period_v['serial'].'已使用'];
                                    }
                                    $serial_code[] = $period_period_v['serial'];
                                    $goods_serial[] = [
                                        'goods_code'    =>$detail['goods_code'],
                                        'stores_id'     =>$period_data_v['stores_id'],
                                        'attribute_id'  =>$period_data_v['attr_id'],
                                        'serial'        =>$period_period_v['serial'],
                                        'remark'        =>$period_period_v['remark'],
                                        'store_status'  =>'1',
                                    ];
                                    $serial_log[] = [
                                        'stores_id'     =>$period_data_v['stores_id'],
                                        'attribute_id'  =>$period_data_v['attr_id'],
                                        'serial'        =>$period_period_v['serial'],
                                        'business_type' =>'1',
                                        'store_status'  =>'1',
                                    ];
                                }
                            }
                            $goods_stock[] = [
                                'goods_code'    =>$detail['goods_code'],
                                'stores_id'     =>$period_data_v['stores_id'],
                                'attribute_id'  =>$period_data_v['attr_id'],
                                'address'       =>$period_data_v['address'],
                                'registration'  =>$period_data_v['registration'],
                                'production'    =>$period_data_v['production'],
                                'period'        =>(float)$period_data_v['period'],
                                'stock'         =>(float)$period_data_v['period'],
                                'unit_cost'     =>(float)$period_data_v['unit_cost'],
                                'price'         =>(float)$period_data_v['price'],
                            ];
                            $goods_stock_log[] = [
                                'business_type' => '1',
                                'goods_id'      => '',
                                'goods_code'    => $detail['goods_code'],
                                'attribute_id'  => $period_data_v['attr_id'],
                                'goods_unit'    => $detail['unit_id'],
                                'stores_id'     => $period_data_v['stores_id'],
                                'remark'        => $detail['note'],
                                'balance_basics'=> (float)$period_data_v['period'],
                                'balance_unit'  => (float)$period_data_v['unit_cost'],
                                'balance_cost'  => (float)$period_data_v['price'],
                            ];
                            $inventory += (float)$period_data_v['period'];
                            $price     += (float)$period_data_v['price'];
                        }
                    }
                    $detail['inventory'] = $inventory;
                    $params['period'] = $inventory;
                    $detail['price'] = $price;
                    $params['unit_cost'] = $inventory>0?(round(($price/$inventory),4)):0;

                    $detail['goods_specification_id'] = isset($detail['goods_spec'])?$detail['goods_spec']:'';

                    $result = false;
                    Db::startTrans();
                    try {
                        $res = $model->allowField(true)->save($detail);
                        $result = $model->id;//商品ID

                        //属性
                        $attr_id = [];
                        if(!empty($combination)){
                            foreach ($combination as $k=>$v){
                                $combination[$k]['createtime'] = time();
                                $combination[$k]['updatetime'] = time();
                            }
                            foreach ($combination as $k=>$v){
                                $attr_id[$v['attr_ids']] = Db::name('kuyou_aux_combination')->insertGetId($v);
                            }
                        }
                        $attr_arr = [];
                        if(!empty($goods_attr)){
                            foreach ($goods_attr as $k=>$v){
                                $attrModel = new GoodsAttr();
                                if(!isset($attr_id[$v['attr_id']]) && $detail['auxiliary']==1){
                                    return ['status'=>500,'msg'=>'属性数据错误'];
                                }
                                $goods_attr[$k]['goods_id'] = $result;
                                $goods_attr[$k]['attribute_id'] = $attr_id[$v['attr_id']];
                                $goods_attr[$k]['createtime'] = time();
                                $goods_attr[$k]['updatetime'] = time();
                                $attrModel->allowField(true)->save($goods_attr[$k]);
                                $attr_arr[$v['attr_id']] = $attrModel->id;
                                //序列号跟踪
                            }
                        }

                        //序列号跟踪
                        if(!empty($serial_log)){
                            foreach ($serial_log as $k=>$v){
                                if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                    return ['status'=>500,'msg'=>'属性数据错误'];
                                }
                                $serial_log[$k]['goods_id'] = $result;
                                $serial_log[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                $serial_log[$k]['createtime'] = time();
                                $serial_log[$k]['updatetime'] = time();
                            }
                            Db::name('kuyou_goods_serial_log')->insertAll($serial_log);
                        }

                        //批次
                        if(!empty($goods_batch)){
                            foreach ($goods_batch as $k=>$v){
                                if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                    return ['status'=>500,'msg'=>'属性数据错误'];
                                }
                                $v['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;

                                $address = $v['address'];
                                $registration = $v['registration'];
                                $production = $v['production'];
                                unset($v['address']);unset($v['registration']);unset($v['production']);

                                $v['goods_id'] = $result;
                                $batch_id = Db::name('kuyou_goods_batch')->insertGetId([
                                    'goods_id' => $result,
                                    'goods_code' => $v['goods_code'],
                                    'attribute_id' => $v['attribute_id'],
                                    'stores_id' => $v['stores_id'],
                                    'batch_name' => $v['batch_name'],
                                    'manufacture' => strtotime($v['manufacture']),
                                    'guarantee' => $v['guarantee'],
                                    'validity' => strtotime($v['validity']),
                                    'address' => $address,
                                    'registration' => $registration,
                                    'production' => $production,
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                ]);
                                Db::name('kuyou_goods_batch_stock')->insert([
                                    'batch_id' => $batch_id,
                                    'goods_id' => $result,
                                    'goods_code' => $v['goods_code'],
                                    'attribute_id' => $v['attribute_id'],
                                    'stores_id' => $v['stores_id'],
                                    'stock' => $v['stock'],
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                ]);
                                Db::name('kuyou_goods_batch_log')->insert([
                                    'goods_id'      => $result,
                                    'goods_unit'    => $detail['unit_id'],
                                    'stores_id'     => $v['stores_id'],
                                    'batch_id'      => (float)$batch_id,
                                    'number'        => (float)$v['stock'],
                                    'business_type' => '1',
                                    'order_id'      => $result,
                                    'createtime'    => time(),
                                    'updatetime'    => time(),
                                ]);
                            }
                        }

                        if(!empty($goods_price)){
                            foreach ($goods_price as $k=>$v){
                                $goods_price[$k]['goods_id'] = $result;
                            }
                            Db::name('kuyou_goods_price')->insertAll($goods_price);
                        }

                        //库存预警
                        if(!empty($goods_stock_warning)){
                            foreach ($goods_stock_warning as $k=>$v){
                                $goods_stock_warning[$k]['goods_id'] = $result;
                                $goods_stock_warning[$k]['createtime'] = time();
                                $goods_stock_warning[$k]['updatetime'] = time();
                            }
                            Db::name('kuyou_goods_stock_warning')->insertAll($goods_stock_warning);
                        }

                        if(!empty($goods_stock)){
                            foreach ($goods_stock as $k=>$v){
                                $goods_stock[$k]['goods_id'] = $result;
                                if(!empty($v['attribute_id'])){
                                    if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                        return ['status'=>500,'msg'=>'属性数据错误'];
                                    }
                                    $goods_stock[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                }else{
                                    $goods_stock[$k]['attribute_id'] = 0;
                                }
                            }
                            Db::name('kuyou_goods_period')->insertAll($goods_stock);
                            foreach ($goods_stock as $k=>$v){
                                $goods_stock[$k]['cost_money'] = $v['price'];
                            }
                            Db::name('kuyou_goods_stock')->insertAll($goods_stock);
                        }
                        //商品收发详情
                        if(!empty($goods_stock_log)){
                            foreach ($goods_stock_log as $k=>$v){
                                $goods_stock_log[$k]['goods_id'] = $result;
                                if(!empty($v['attribute_id'])){
                                    if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                        return ['status'=>500,'msg'=>'属性数据错误'];
                                    }
                                    $goods_stock_log[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                }else{
                                    $goods_stock_log[$k]['attribute_id'] = 0;
                                }
                            }
                            Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                        }

                        if(!empty($goods_serial)){
                            foreach ($goods_serial as $k=>$v){
                                $goods_serial[$k]['goods_id'] = $result;
                                if(!empty($v['attribute_id'])){
                                    if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                        return ['status'=>500,'msg'=>'属性数据错误'];
                                    }
                                    $goods_serial[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                }else{
                                    $goods_serial[$k]['attribute_id'] = 0;
                                }
                            }
                            Db::name('kuyou_goods_serial')->insertAll($goods_serial);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        return ['status'=>200,'msg'=>$result];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    public static function getSet($name,$field)
    {
        $set = \think\Db::name('kuyou_sets')->where(['name'=>$name])->value($field);
        return $set;
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|商品ID'=>'require|number',
                'goods_code|编号'=>'require',
                'goods_name|名称'=>'require',
                'goods_type_id|商品分类'=>'require',
                'status|状态'=>'require|in:0,1',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['goods_code'],6);//验证编号是否合法
                if($status){
                    $detail['more_unit'] = isset($detail['more_unit'])?$detail['more_unit']:0;
                    $detail['stock_warning'] = isset($detail['stock_warning'])?$detail['stock_warning']:0;
                    $detail['batch'] = isset($detail['batch'])?$detail['batch']:0;
                    $detail['serial'] = isset($detail['serial'])?$detail['serial']:0;
                    $model = new Goods();
                    $row = $model->get($detail['id']);
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'您要修改的数据不存在'];
                    }
                    $oldCode = $row['goods_code'];

                    $goods = $model->where(['goods_code'=>$detail['goods_code'],'id'=>['<>',$detail['id']]])->value('id');
                    if($goods){
                        return ['status'=>500,'msg'=>'商品编号已使用'];
                    }

                    if(isset($detail['goods_barcode']) && !empty($detail['goods_barcode'])){//商品条码
                        $barcode = \think\Db::name('kuyou_goods')->where(['goods_barcode'=>$detail['goods_barcode'],'goods_code'=>['<>',$oldCode]])->value('id');
                        if($barcode){
                            return ['status'=>500,'msg'=>'商品条码已被使用'];
                        }
                    }

                    if(isset($detail['goods_type_id']) && !empty($detail['goods_type_id'])){//选择了商品分类
                        $goods_type_id = $detail['goods_type_id'];
                        $goods_type = (new GoodsType())->where(['id'=>$goods_type_id])->value('id');
                        if(empty($goods_type)){
                            return ['status'=>500,'msg'=>'商品分类不存在'];
                        }
                    }

                    if(isset($detail['manager_warehouse_id']) && !empty($detail['manager_warehouse_id'])){//选择了商品默认仓库
                        $id = $detail['manager_warehouse_id'];
                        $stores = (new Stores())->where(['id'=>$id])->value('id');
                        if(empty($stores)){
                            return ['status'=>500,'msg'=>'首选仓库不存在'];
                        }
                    }

                    $more_unit = isset($detail['more_unit'])?$detail['more_unit']:2;
                    $more_unit = empty($more_unit)?2:$more_unit;
                    $goods_price = [];//多单位&价格设置
                    if($more_unit==2){//单计量单位
                        if(isset($detail['unit_id']) && !empty($detail['unit_id'])){//选择了商品单位
                            $id = $detail['unit_id'];
                            $unit = (new Unit())->where(['id'=>$id])->value('id');
                            if(empty($unit)){
                                return ['status'=>500,'msg'=>'商品单位不存在'];
                            }
                        }
                        if(!isset($detail['price_data']) || (isset($detail['price_data']) && empty($detail['price_data']))){
                            return ['status'=>500,'msg'=>'请设置商品价格策略'];
                        }else{
                            if(!is_array($detail['price_data'])){
                                $price_data = (array)json_decode(html_entity_decode($detail['price_data']), true);
                                $price_data = isset($price_data[0])?$price_data[0]:$price_data;
                            }else{
                                $price_data = $detail['price_data'];
                            }
                            $check = (new Commons())->checkParameter($price_data,[
                                'market_sell_price|零售价'=>'require|money',
                                'wholesale_price|批发价'=>'require|money',
                                'vip_price|VIP会员价'=>'require|money',
                                'discount|折扣率1'=>'require|money',
                                'discount2|折扣率2'=>'require|money',
                                'purchase|预计采购价'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }else{
                                $detail['market_sell_price'] = $price_data['market_sell_price'];
                                $detail['wholesale_price'] = $price_data['wholesale_price'];
                                $detail['vip_price'] = $price_data['vip_price'];
                                $detail['discount'] = $price_data['discount'];
                                $detail['discount2'] = $price_data['discount2'];
                                $detail['purchase'] = $price_data['purchase'];
                            }
                        }
                    }else{//多计量单位
                        if(!isset($detail['more_unit_id']) || (isset($detail['more_unit_id']) && empty($detail['more_unit_id']))){
                            return ['status'=>500,'msg'=>'请选择商品多单位'];
                        }else{
                            $id = $detail['more_unit_id'];
                            $detail['unit_id'] = $id;
                            $arr = [];

                            $unit_id = [];
                            $unit = (new Unit())->where(['id'=>$id])->value('id');
                            if(empty($unit)){
                                return ['status'=>500,'msg'=>'商品单位不存在'];
                            }
                            $arr[] = ['id'=>$unit,'advance_rate'=>1];$unit_id[] = $unit;

                            $unit_data = collection((new UnitConversions())
                                ->where(['main_unit'=>$id])
                                ->order('advance_rate','ASC')
                                ->field('vice_unit as id,advance_rate')->select())->toArray();
                            if(empty($unit_data)){
                                return ['status'=>500,'msg'=>'商品多单位不存在'];
                            }
                            foreach ($unit_data as $unit_k=>$unit_v){
                                $arr[] = $unit_v;$unit_id[] = $unit_v['id'];
                            }
                            if(!is_array($detail['more_unit_data'])){
                                $data = (array)json_decode(html_entity_decode($detail['more_unit_data']), true);
                            }else{
                                $data = $detail['more_unit_data'];
                            }
                            foreach ($data as $data_k=>$data_v){
                                $check = (new Commons())->checkParameter($data_v,[
                                    'unit|多单位'=>'require|number',
                                    'market_sell_price|零售价'=>'require|money',
                                    'wholesale_price|批发价'=>'require|money',
                                    'vip_price|VIP会员价'=>'require|money',
                                    'discount|折扣率1'=>'require|money',
                                    'discount2|折扣率2'=>'require|money',
                                    'purchase|预计采购价'=>'require|money',
                                ]);
                                if(isset($check['status'])){
                                    return $check;
                                }
                                if(!in_array($data_v['unit'],$unit_id)){
                                    return ['status'=>500,'msg'=>'商品多单位设置错误'];
                                }
                                $goods_price[] = [
                                    'goods_code'=>$detail['goods_code'],
                                    'goods_name'=>$detail['goods_name'],
                                    'goods_barcode'=>$detail['goods_barcode'],
                                    'unit'=>$data_v['unit'],
                                    'market_sell_price'=>$data_v['market_sell_price'],
                                    'wholesale_price'=>$data_v['wholesale_price'],
                                    'vip_price'=>$data_v['vip_price'],
                                    'discount'=>$data_v['discount'],
                                    'discount2'=>$data_v['discount2'],
                                    'purchase'=>$data_v['purchase'],
                                    'is_default'=>($data_v['unit']==$id?'1':'0'),
                                ];
                            }
                            $detail['market_sell_price'] = $data[0]['market_sell_price'];
                            $detail['wholesale_price'] = $data[0]['wholesale_price'];
                            $detail['vip_price'] = $data[0]['vip_price'];
                            $detail['discount'] = $data[0]['discount'];
                            $detail['discount2'] = $data[0]['discount2'];
                            $detail['purchase'] = $data[0]['purchase'];
                            $detail['unit_id'] = $data[0]['unit'];
                        }
                    }

                    $goods_stock_warning = [];//预警设置
                    if($detail['stock_warning']==1 && $detail['branch']==1){
                        if(!is_array($detail['stock_data'])){
                            $stock_data = (array)json_decode(html_entity_decode($detail['stock_data']), true);
                        }else{
                            $stock_data = $detail['stock_data'];
                        }
                        foreach ($stock_data as $k=>$v){
                            $check = (new Commons())->checkParameter($v,[
                                'stores_id|仓库'=>'require|number',
                                'min_stock|最小库存'=>'require|money',
                                'max_stock|最大库存'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }
                            $goods_stock_warning[] = [
                                'goods_id'    => '',
                                'goods_code'  => $detail['goods_code'],
                                'stores_id'=>$v['stores_id'],
                                'min_stock'=>$v['min_stock'],
                                'max_stock'=>$v['max_stock'],
                            ];
                        }
                    }

                    $combination = [];//属性组合记录
                    $combination_id = [];//属性组合ID
                    $auxiliary_id = [];//所有属性组合ID
                    $goods_attr = [];//属性价格
                    if($detail['auxiliary']==1 && self::getSet('auxiliary','is_checked')==1){
                        $auxiliary_type = explode(',',$detail['auxiliary_type']);
                        $arr = Db::name('kuyou_auxiliary')->where(['id'=>['in',$detail['auxiliary_type']]])->field('id,name')->select();
                        if(sizeof($arr)!=sizeof($auxiliary_type)){
                            return ['status'=>500,'msg'=>'一级属性选择错误'];
                        }
                        $auxiliary_type_c = explode(',',$detail['auxiliary_type_c']);
                        $arr = Db::name('kuyou_auxiliary')->where(['id'=>['in',$detail['auxiliary_type_c']]])->field('id,name')->select();
                        if(sizeof($arr)!=sizeof($auxiliary_type_c)){
                            return ['status'=>500,'msg'=>'二级属性选择错误'];
                        }
                        $detail['auxiliary_type'] = serialize($auxiliary_type);
                        $detail['auxiliary_type_c'] = serialize($auxiliary_type_c);
                        $auxiliary = self::auxiliary($auxiliary_type,$auxiliary_type_c);
                        foreach ($auxiliary as $auxiliary_k=>$auxiliary_v){
                            $auxiliary_v_id = explode('&',$auxiliary_v['id']);
                            sort($auxiliary_v_id);
                            $auxiliary_id[] = implode('&',$auxiliary_v_id);
                        }
                        if(!is_array($detail['auxiliary_data'])){
                            $auxiliary_data = (array)json_decode(html_entity_decode($detail['auxiliary_data']), true);
                        }else{
                            $auxiliary_data = $detail['auxiliary_data'];
                        }
                        foreach ($auxiliary_data as $k=>$v){
                            $auxiliary_v_id = explode('&',$v['attr_id']);
                            sort($auxiliary_v_id);
                            $v['attr_id'] = implode('&',$auxiliary_v_id);

                            if(!in_array($v['attr_id'],$auxiliary_id) || empty($v['attr_id'])){
                                return ['status'=>500,'msg'=>'属性价格设置错误'];
                            }else if(in_array($v['attr_code'],$combination_id) || empty($v['attr_code'])){
                                return ['status'=>500,'msg'=>'属性编号重复'];
                            }else{
                                $combination[] = [
                                    'attr_ids'  => $v['attr_id'],
                                    'attr_code' => $v['attr_code'],
                                ];
                                $combination_id[] = $v['attr_code'];
                                $v['goods_code'] = $detail['goods_code'];
                                $v['goods_name'] = $detail['goods_name'];
                                $v['goods_barcode'] = $detail['goods_barcode'];
                                $v['goods_code'] = $detail['goods_code'];
                                $v['unit'] = $detail['unit_id'];
                                $goods_attr[] = $v;
                            }
                        }
                        $status = Db::name('kuyou_goods_attr')->where(['attr_code'=>['in',$combination_id],'goods_code'=>['<>',$oldCode]])->find();
                        if($status){
                            return ['status'=>500,'msg'=>'商品属性编号已占用'];
                        }
                    }

                    if($detail['batch']==1 && $detail['serial']==1){
                        return ['status'=>500,'msg'=>'商品不能同时启用批次管理和序列号管理'];
                    }

                    //启用批次保质期管理
                    $goods_batch = [];
                    if($detail['batch']==1 && self::getSet('batch','is_checked')==1){
                        if (empty($detail['shelf_life'])){
                            return ['status'=>500,'msg'=>'请输入保质期天数'];
                        }
                        if (empty($detail['early_warning'])){
                            return ['status'=>500,'msg'=>'请输入预警天数'];
                        }
                    }

                    $goods_stock = [];//商品库存
                    $goods_stock_log = [];//库存记录

                    $detail['period_status'] = isset($detail['period_status'])?$detail['period_status']:0;
                    //启用商品序列号
                    $goods_serial = [];
                    $serial_log = [];
                    $serial_code = [];
                    $inventory = 0;//期初库存
                    $price = 0;//期初余额
                    if(!empty($detail['period_data']) && $detail['period_status']==1){
                        if(!is_array($detail['period_data'])){
                            $period_data = (array)json_decode(html_entity_decode($detail['period_data']), true);
                        }else{
                            $period_data = $detail['period_data'];
                        }
                        foreach ($period_data as $period_data_k=>$period_data_v){
                            $check = (new Commons())->checkParameter($period_data_v,[
                                'stores_id|仓库'=>'require|number',
                                'period|期初数量'=>'require|money',
                                'unit_cost|单位成本'=>'require|money',
                                'price|期初总价'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }

                            $auxiliary_v_id = explode('&',$period_data_v['attr_id']);
                            sort($auxiliary_v_id);
                            $period_data_v['attr_id'] = implode('&',$auxiliary_v_id);

                            if(!in_array($period_data_v['attr_id'],$auxiliary_id) && $detail['auxiliary']==1){
                                return ['status'=>500,'msg'=>'期初选择属性错误'];
                            }
                            if($detail['batch']==1 && self::getSet('batch','is_checked')==1){
                                $check = (new Commons())->checkParameter($period_data_v,[
                                    'batch_name|批次'=>'require',
                                    'manufacture|生产日期'=>'require',
                                    'validity|到期时间'=>'require',
                                ]);
                                if(isset($check['status'])){
                                    return $check;
                                }
                                $goods_batch[] = [
                                    'goods_id'    => '',
                                    'goods_code'  => $detail['goods_code'],
                                    'attribute_id'=> $period_data_v['attr_id'],
                                    'stores_id'   => $period_data_v['stores_id'],
                                    'stock'       => (float)$period_data_v['period'],
                                    'number'      => (float)$period_data_v['period'],
                                    'batch_name'  => $period_data_v['batch_name'],
                                    'manufacture' => $period_data_v['manufacture'],
                                    'guarantee'   => $detail['shelf_life'],
                                    'validity'    => $period_data_v['validity'],
                                    'type'        => 1,
                                    'address'     =>$period_data_v['address'],
                                    'registration'=>$period_data_v['registration'],
                                    'production'  =>$period_data_v['production'],
                                ];
                            }
                            //序列号
                            if($detail['serial']==1 && (isset($period_data_v['serial']) && empty($period_data_v['serial']) || !isset($period_data_v['serial']))  && getSet('serial','is_checked')==1){
                                return ['status'=>500,'msg'=>'请输入商品序列号'];
                            }
                            if($detail['serial']==1 && isset($period_data_v['serial']) && !empty($period_data_v['serial']) && self::getSet('serial','is_checked')==1){
                                $period_period = $period_data_v['serial'];
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $status = Db::name('kuyou_goods_serial')->where(['serial'=>$period_period_v['serial'],'goods_code'=>['<>',$oldCode]])->find();
                                    if($status){
                                        return ['status'=>500,'msg'=>'商品序列号'.$period_period_v['serial'].'已使用'];
                                    }
                                    $serial_code[] = $period_period_v['serial'];
                                    $goods_serial[] = [
                                        'goods_code'    =>$detail['goods_code'],
                                        'stores_id'     =>$period_data_v['stores_id'],
                                        'attribute_id'  =>$period_data_v['attr_id'],
                                        'serial'        =>$period_period_v['serial'],
                                        'remark'        =>$period_period_v['remark'],
                                        'store_status'  =>'1',
                                    ];
                                    $serial_log[] = [
                                        'stores_id'     =>$period_data_v['stores_id'],
                                        'attribute_id'  =>$period_data_v['attr_id'],
                                        'serial'        =>$period_period_v['serial'],
                                        'business_type' =>'1',
                                        'store_status'  =>'1',
                                    ];
                                }
                            }
                            $goods_stock[] = [
                                'goods_code'    =>$detail['goods_code'],
                                'stores_id'     =>$period_data_v['stores_id'],
                                'attribute_id'  =>$period_data_v['attr_id'],
                                'address'       =>$period_data_v['address'],
                                'registration'  =>$period_data_v['registration'],
                                'production'    =>$period_data_v['production'],
                                'period'        =>(float)$period_data_v['period'],
                                'stock'         =>(float)$period_data_v['period'],
                                'unit_cost'     =>(float)$period_data_v['unit_cost'],
                                'price'         =>(float)$period_data_v['price'],
                            ];
                            $goods_stock_log[] = [
                                'business_type' => '1',
                                'goods_id'      => '',
                                'goods_code'    => $detail['goods_code'],
                                'attribute_id'  => $period_data_v['attr_id'],
                                'goods_unit'    => $detail['unit_id'],
                                'stores_id'     => $period_data_v['stores_id'],
                                'remark'        => $detail['note'],
                                'balance_basics'=> (float)$period_data_v['period'],
                                'balance_unit'  => (float)$period_data_v['unit_cost'],
                                'balance_cost'  => (float)$period_data_v['price'],
                            ];
                            $inventory += (float)$period_data_v['period'];
                            $price     += (float)$period_data_v['price'];
                        }
                    }
                    $detail['inventory'] = $inventory;
                    $detail['period'] = $inventory;
                    $detail['price'] = $price;
                    $detail['unit_cost'] = $inventory>0?(round(($price/$inventory),4)):0;
                    
                    $check = self::checkRow($detail['id']);
                    if(isset($check['status'])){
                        if($row['goods_code']!=$detail['goods_code']){
                            $msg = '此商品已参与核算，不可编辑商品编号';
                        }
                        if($row['goods_barcode']!=$detail['goods_barcode']){
                            $msg = '此商品已参与核算，不可编辑商品条码';
                        }
                        if($row['more_unit']!=$detail['more_unit']){
                            $msg = '此商品已参与核算，不可编辑商品单位';
                        }else{
                            if($row['more_unit']==1 && $row['more_unit_id']!=$detail['more_unit_id']){
                                $msg = '此商品已参与核算，不可编辑商品单位';
                            }
                            if($row['more_unit']!=1 && $row['unit_id']!=$detail['unit_id']){
                                $msg = '此商品已参与核算，不可编辑商品单位';
                            }
                        }
                        if($row['period_status']!=$detail['period_status']){
                            $msg = '此商品已参与核算，不可编辑商品期初数据';
                        }else{
                            if($detail['period_status']==1){
                                if($row['period']!=$detail['period'] || $row['unit_cost']!=$detail['unit_cost'] || $row['price']!=$detail['price'] || $row['period_status']!=$detail['period_status']){
                                    $msg = '此商品已参与核算，不可编辑商品期初数据';
                                }
                            }
                        }
                        if($row['auxiliary']!=$detail['auxiliary']){
                            if($detail['auxiliary']==1 && ($row['auxiliary_type']!=$detail['auxiliary_type'] || $row['auxiliary_type_c']!=$detail['auxiliary_type_c'])){
                                $msg = '此商品已参与核算，不可编辑商品属性';
                            }
                        }
                        if($detail['batch']!=1){
                            $detail['shelf_life'] = 0;$detail['early_warning'] = 0;
                        }
                        if($row['batch']!=$detail['batch'] || $row['shelf_life']!=$detail['shelf_life'] || $row['early_warning']!=$detail['early_warning']){
                            $msg = '此商品已参与核算，不可编辑商品批次信息';
                        }
                        if($row['serial']!=$detail['serial']){
                            $msg = '此商品已参与核算，不可编辑商品序列号信息';
                        }
                        if(isset($msg)){
                            return ['status'=>500,'msg'=>$msg];
                        }
                    }

                    $detail['goods_specification_id'] = isset($detail['goods_spec'])?$detail['goods_spec']:'';

                    $res = false;
                    Db::startTrans();
                    try {
                        $serial = Db::name('kuyou_goods_serial_log')->where(['goods_id'=>$row['id'],'business_type'=>'1'])->column('serial');
                        $goods_batch_id = Db::name('kuyou_goods_batch_log')->where(['goods_id'=>$row['id'],'business_type'=>'1'])->column('batch_id');
                        $where = [];$where['goods_id'] = $row['id'];
                        Db::name('kuyou_goods_stock')->where($where)->delete();
                        Db::name('kuyou_goods_attr')->where($where)->delete();
                        Db::name('kuyou_goods_batch')->where($where)->where(['id'=>['in',$goods_batch_id]])->delete();
                        Db::name('kuyou_goods_price')->where($where)->delete();
                        Db::name('kuyou_goods_stock_warning')->where($where)->delete();
                        Db::name('kuyou_goods_serial')->where($where)->where(['serial'=>['in',$serial]])->delete();
                        Db::name('kuyou_goods_period')->where($where)->delete();
                        Db::name('kuyou_goods_log')->where($where)->delete();
                        Db::name('kuyou_goods_serial_log')->where($where)->where(['business_type'=>'1'])->delete();
                        Db::name('kuyou_goods_batch_stock')->where($where)->where(['batch_id'=>['in',$goods_batch_id]])->delete();
                        Db::name('kuyou_goods_batch_log')->where($where)->where(['business_type'=>'1'])->delete();

                        $detail['updatetime'] = time();
                        $res = $row->allowField(true)->save($detail);
                        $result = $row['id'];//商品ID

                        //属性
                        $attr_id = [];
                        if(!empty($combination)){
                            foreach ($combination as $k=>$v){
                                $combination[$k]['createtime'] = time();
                                $combination[$k]['updatetime'] = time();
                            }
                            foreach ($combination as $k=>$v){
                                $attr_id[$v['attr_ids']] = Db::name('kuyou_aux_combination')->insertGetId($v);
                            }
                        }
                        $attr_arr = [];
                        if(!empty($goods_attr)){
                            foreach ($goods_attr as $k=>$v){
                                $attrModel = new GoodsAttr();
                                if(!isset($attr_id[$v['attr_id']]) && $detail['auxiliary']==1){
                                    return ['status'=>500,'msg'=>'属性数据错误'];
                                }
                                $goods_attr[$k]['goods_id'] = $result;
                                $goods_attr[$k]['attribute_id'] = $attr_id[$v['attr_id']];
                                $goods_attr[$k]['createtime'] = time();
                                $goods_attr[$k]['updatetime'] = time();
                                $attrModel->allowField(true)->save($goods_attr[$k]);
                                $attr_arr[$v['attr_id']] = $attrModel->id;
                                //序列号跟踪
                            }
                        }

                        //序列号跟踪
                        if(!empty($serial_log)){
                            foreach ($serial_log as $k=>$v){
                                if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                    return ['status'=>500,'msg'=>'属性数据错误'];
                                }
                                $serial_log[$k]['goods_id'] = $result;
                                $serial_log[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                $serial_log[$k]['createtime'] = time();
                                $serial_log[$k]['updatetime'] = time();
                            }
                            Db::name('kuyou_goods_serial_log')->insertAll($serial_log);
                        }

                        //批次
                        if(!empty($goods_batch)){
                            foreach ($goods_batch as $k=>$v){
                                if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                    return ['status'=>500,'msg'=>'属性数据错误3'];
                                }
                                $v['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;

                                $address = $v['address'];
                                $registration = $v['registration'];
                                $production = $v['production'];
                                unset($v['address']);unset($v['registration']);unset($v['production']);

                                $v['goods_id'] = $result;
                                $batch_id = Db::name('kuyou_goods_batch')->insertGetId([
                                    'goods_id' => $result,
                                    'goods_code' => $v['goods_code'],
                                    'attribute_id' => $v['attribute_id'],
                                    'stores_id' => $v['stores_id'],
                                    'batch_name' => $v['batch_name'],
                                    'manufacture' => strtotime($v['manufacture']),
                                    'guarantee' => $v['guarantee'],
                                    'validity' => strtotime($v['validity']),
                                    'address' => $address,
                                    'registration' => $registration,
                                    'production' => $production,
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                ]);
                                Db::name('kuyou_goods_batch_stock')->insert([
                                    'batch_id' => $batch_id,
                                    'goods_id' => $result,
                                    'goods_code' => $v['goods_code'],
                                    'attribute_id' => $v['attribute_id'],
                                    'stores_id' => $v['stores_id'],
                                    'stock' => $v['stock'],
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                ]);
                                Db::name('kuyou_goods_batch_log')->insert([
                                    'goods_id'      => $result,
                                    'goods_unit'    => $detail['unit_id'],
                                    'stores_id'     => $v['stores_id'],
                                    'batch_id'      => (float)$batch_id,
                                    'number'        => (float)$v['stock'],
                                    'business_type' => '1',
                                    'order_id'      => $result,
                                    'createtime'    => time(),
                                    'updatetime'    => time(),
                                ]);
                            }
                        }

                        if(!empty($goods_price)){
                            foreach ($goods_price as $k=>$v){
                                $goods_price[$k]['goods_id'] = $result;
                            }
                            Db::name('kuyou_goods_price')->insertAll($goods_price);
                        }

                        //库存预警
                        if(!empty($goods_stock_warning)){
                            foreach ($goods_stock_warning as $k=>$v){
                                $goods_stock_warning[$k]['goods_id'] = $result;
                                $goods_stock_warning[$k]['createtime'] = time();
                                $goods_stock_warning[$k]['updatetime'] = time();
                            }
                            Db::name('kuyou_goods_stock_warning')->insertAll($goods_stock_warning);
                        }

                        if(!empty($goods_stock)){
                            foreach ($goods_stock as $k=>$v){
                                $goods_stock[$k]['goods_id'] = $result;
                                if(!empty($v['attribute_id'])){
                                    if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                        return ['status'=>500,'msg'=>'属性数据错误'];
                                    }
                                    $goods_stock[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                }else{
                                    $goods_stock[$k]['attribute_id'] = 0;
                                }
                            }
                            Db::name('kuyou_goods_period')->insertAll($goods_stock);
                            foreach ($goods_stock as $k=>$v){
                                $goods_stock[$k]['cost_money'] = $v['price'];
                            }
                            Db::name('kuyou_goods_stock')->insertAll($goods_stock);
                        }
                        //商品收发详情
                        if(!empty($goods_stock_log)){
                            foreach ($goods_stock_log as $k=>$v){
                                $goods_stock_log[$k]['goods_id'] = $result;
                                if(!empty($v['attribute_id'])){
                                    if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                        return ['status'=>500,'msg'=>'属性数据错误'];
                                    }
                                    $goods_stock_log[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                }else{
                                    $goods_stock_log[$k]['attribute_id'] = 0;
                                }
                            }
                            Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                        }

                        if(!empty($goods_serial)){
                            foreach ($goods_serial as $k=>$v){
                                $goods_serial[$k]['goods_id'] = $result;
                                if(!empty($v['attribute_id'])){
                                    if(!isset($attr_arr[$v['attribute_id']]) && $detail['auxiliary']==1){
                                        return ['status'=>500,'msg'=>'属性数据错误'];
                                    }
                                    $goods_serial[$k]['attribute_id'] = isset($attr_arr[$v['attribute_id']])?$attr_arr[$v['attribute_id']]:0;
                                }else{
                                    $goods_serial[$k]['attribute_id'] = 0;
                                }
                            }
                            Db::name('kuyou_goods_serial')->insertAll($goods_serial);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($res){
                        return ['status'=>200,'msg'=>'更新成功'];
                    }else{
                        return ['status'=>500,'msg'=>'更新失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 批量更新
     * @param array $detail
     * @return array
     */
    public static function editDetails($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|商品ID'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $goods = (new Goods())->where(['id'=>['in',$detail['id']]])->select();
                $data = [];$goods_stock_warning = [];
                foreach ($goods as $goods_k=>$goods_v){
                    $row = [];
                    $check = self::checkRow($goods_v['id']);
                    if(isset($check['status'])){
                        return ['status'=>500,'msg'=>$check['msg'].'，不可编辑'];
                    }elseif ($goods_v['period_status']==1 && $detail['serial_status']==1){
                        return ['status'=>500,'msg'=>$goods_v['goods_name'].'设置了期初信息，不可编辑序列号'];
                    }
                    $row['id'] = $goods_v['id'];
                    if($detail['auxiliary_status']==1 && !empty($detail['auxiliary_type'])){
                        if ($goods_v['period_status']==1){
                            return ['status'=>500,'msg'=>$goods_v['goods_name'].'设置了期初信息，不可编辑属性'];
                        }
                        $auxiliary_type = explode(',',$detail['auxiliary_type']);
                        $arr = Db::name('kuyou_auxiliary')->where(['id'=>['in',$detail['auxiliary_type']]])->field('id,name')->select();
                        if(sizeof($arr)!=sizeof($auxiliary_type)){
                            return ['status'=>500,'msg'=>'属性选择错误'];
                        }
                        $row['auxiliary_type'] = serialize($auxiliary_type);
                        $row['auxiliary_type_c'] = '';
                        $row['auxiliary'] = 1;
                    }else{
                        $row['auxiliary'] = 0;
                        $row['auxiliary_type'] = '';
                        $row['auxiliary_type_c'] = '';
                    }
                    if($detail['batch_status']==1 && $detail['serial_status']==1){
                        return ['status'=>500,'msg'=>'商品不能同时启用批次管理和序列号管理'];
                    }

                    //启用批次保质期管理
                    if($detail['batch_status']==1 && self::getSet('batch','is_checked')==1){
                        if (empty($detail['shelf_life'])){
                            return ['status'=>500,'msg'=>'请输入保质期天数'];
                        }
                        if (empty($detail['early_warning'])){
                            return ['status'=>500,'msg'=>'请输入预警天数'];
                        }
                        $row['shelf_life'] = $detail['shelf_life'];
                        $row['early_warning'] = $detail['early_warning'];
                    }

                    if(!empty($detail['manager_warehouse_id'])){
                        $row['manager_warehouse_id'] = $detail['manager_warehouse_id'];
                    }

                    if(!empty($detail['goods_type_id'])){
                        $row['goods_type_id'] = $detail['goods_type_id'];
                    }

                    //预警设置  不分仓
                    if($detail['stock_warning']==1 && $detail['branch']!=1){
                        $row['stock_warning'] = $detail['stock_warning'];
                        $row['branch'] = $detail['branch'];
                        $row['min_stock'] = $detail['min_stock'];
                        $row['max_stock'] = $detail['max_stock'];
                    }
                    //预警设置  分仓
                    if($detail['stock_warning']==1 && $detail['branch']==1){
                        if(!is_array($detail['stock_data'])){
                            $stock_data = (array)json_decode(html_entity_decode($detail['stock_data']), true);
                        }else{
                            $stock_data = $detail['stock_data'];
                        }
                        foreach ($stock_data as $k=>$v){
                            $check = (new Commons())->checkParameter($v,[
                                'stores_id|仓库'=>'require|number',
                                'min_stock|最小库存'=>'require|money',
                                'max_stock|最大库存'=>'require|money',
                            ]);
                            if(isset($check['status'])){
                                return $check;
                            }
                            $goods_stock_warning[] = [
                                'goods_id'      => $goods_v['id'],
                                'goods_code'    => $goods_v['goods_code'],
                                'stores_id'     => $v['stores_id'],
                                'min_stock'     => $v['min_stock'],
                                'max_stock'     => $v['max_stock'],
                                'createtime'    => time(),
                                'updatetime'    => time(),
                            ];
                        }
                        $row['stock_warning'] = $detail['stock_warning'];
                        $row['branch'] = $detail['branch'];
                        $row['note'] = $goods_v['note'];
                    }
                    $data[] = $row;
                }
                $res = false;
                Db::startTrans();
                try {
                    $where = ['goods_id'=>['in',$detail['id']]];
                    Db::name('kuyou_goods_attr')->where($where)->delete();
                    Db::name('kuyou_goods_price')->where($where)->delete();
                    Db::name('kuyou_goods_stock_warning')->where($where)->delete();

                    $detail['updatetime'] = time();
                    $res = (new Goods())->allowField(true)->saveAll($data);

                    //库存预警
                    if(!empty($goods_stock_warning)){
                        Db::name('kuyou_goods_stock_warning')->insertAll($goods_stock_warning);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    return ['status'=>500,'msg'=>$e->getMessage()];
                }
                if($res){
                    return ['status'=>200,'msg'=>'更新成功'];
                }else{
                    return ['status'=>500,'msg'=>'更新失败'];
                }
            }
        }
    }

    /**
     * 校验商品是否可修改/删除
     * @param string $id
     * @return array|bool
     */
    public static function checkRow($id=null,$code=null){
        if(empty($id) && empty($code)){
            return ['status'=>500,'msg'=>'未查询到商品数据'];
        }
        $model = new Goods();
        if(!empty($id)){
            $row = $model->get($id);
        }else{
            $row = $model->where(['goods_code'=>$code])->find();
        }
        if(empty($row)){
            return ['status'=>400,'msg'=>'未查询到商品数据'];
        }
        $goods_code = $row['goods_code'];

        $order_info = Db::name('kuyou_goods_purchase_order_info')->where(['goods_code'=>$goods_code])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有购货订单'];
        }
        $order_info = Db::name('kuyou_goods_purchase_info')->where(['goods_code'=>$goods_code])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有购货单'];
        }
        $order_info = Db::name('kuyou_goods_exchange_info')->where(['goods_code'=>$goods_code])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有购货退货单'];
        }
        $order_info = Db::name('kuyou_goods_sales_order_info')->where(['goods_code'=>$goods_code])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有销货订单'];
        }
        $order_info = Db::name('kuyou_goods_sales_info')->where(['goods_code'=>$goods_code])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有销货单'];
        }
        $order_info = Db::name('kuyou_goods_sales_exchange_info')->where(['goods_code'=>$goods_code])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有销货退货单'];
        }

        $order_info = Db::name('kuyou_warehouse_info')->where(['goods_id'=>$id])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有其他出库单'];
        }
        $order_info = Db::name('kuyou_warehousing_info')->where(['goods_id'=>$id])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有其他出库单'];
        }

        $order_info = Db::name('kuyou_assemble_info')->where(['goods_id'=>$id])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有组装单'];
        }
        $order_info = Db::name('kuyou_split_info')->where(['goods_id'=>$id])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有拆卸单'];
        }
        $order_info = Db::name('kuyou_inventory_info')->where(['goods_id'=>$id])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有盘点单'];
        }
        $order_info = Db::name('kuyou_inventory_serial_info')->where(['goods_id'=>$id])->value('id');
        if(!empty($order_info)){
            return ['status'=>500,'msg'=>$goods_code.'已有序列号盘点单'];
        }
        return true;
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $ids = explode(',',$id);
            foreach ($ids as $k=>$v){
                $check = self::checkRow($v);
                if(isset($check['status'])){
                    return ['status'=>500,'msg'=>$check['msg'].'，不可删除'];
                }
            }
            Db::startTrans();
            try {
                $res = Db::name('kuyou_goods')->where(['id'=>['in',$ids]])->delete();
                $where = ['goods_id'=>['in',$ids]];
                Db::name('kuyou_goods_attr')->where($where)->delete();
                Db::name('kuyou_goods_batch')->where($where)->delete();
                Db::name('kuyou_goods_price')->where($where)->delete();
                Db::name('kuyou_goods_stock_warning')->where($where)->delete();
                Db::name('kuyou_goods_serial')->where($where)->delete();
                Db::name('kuyou_goods_stock')->where($where)->delete();
                Db::name('kuyou_goods_period')->where($where)->delete();
                Db::name('kuyou_goods_log')->where($where)->delete();
                Db::name('kuyou_goods_serial_log')->where($where)->delete();
                Db::name('kuyou_goods_batch_stock')->where($where)->delete();
                Db::name('kuyou_goods_batch_log')->where($where)->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 获取商品价格策略
     * @param int $id 商品ID
     * @return array
     */
    public static function getGoodsPrice($id){
        $model = new Goods();
        $row = $model->where(['id'=>$id,'more_unit'=>'2'])->field('market_sell_price,wholesale_price,vip_price,discount,discount2,purchase')->find();
        if(empty($row)){
            return [];
        }else{
            return $row;
        }
    }

    /**
     * 获取商品多单位以及单位价格
     * @param int $id 商品ID
     * @return array
     */
    public static function getGoodsUnit($id){
        $model = new Goods();
        $row = $model->where(['id'=>$id,'more_unit'=>'1'])->field('more_unit_id,warehousing,warehouse')->find();
        if(empty($row)){
            return [];
        }
        $main_unit = $row['more_unit_id'];
        $unit_list = Db::name('kuyou_unit_conversion')
            ->where(['main_unit'=>$main_unit])
            ->order('advance_rate','ASC')
            ->field('vice_unit,advance_rate')
            ->select();
        $unit_id = [$main_unit];
        foreach ($unit_list as $unit_list_k=>$unit_list_v){
            $unit_id[] = $unit_list_v['vice_unit'];
        }
        $unit_lists = Db::name('kuyou_unit')->where(['id'=>['in',$unit_id]])->field('id,name')->select();
        foreach ($unit_lists as $unit_k=>$unit_v){
            if($unit_v['id']==$main_unit){
                $unit_lists[$unit_k]['advance_rate'] = 1;
            }else{
                foreach ($unit_list as $unit_list_k=>$unit_list_v){
                    if($unit_v['id']==$unit_list_v['vice_unit']){
                        $unit_lists[$unit_k]['advance_rate'] = $unit_list_v['advance_rate'];
                    }
                }
            }
        }
        $row['unit_data'] = $unit_lists;

        $goods_price = Db::name('kuyou_goods_price')->alias('g')
            ->join('kuyou_unit u','u.id=g.unit')
            ->where(['g.goods_id'=>$id])
            ->field('g.unit,g.market_sell_price,g.wholesale_price,g.vip_price,g.discount,g.discount2,g.purchase,g.is_default,u.name')
            ->order('g.is_default DESC')->select();
        $row['goods_price'] = $goods_price;

        return $row;
    }

    /**
     * 获取商品库存预警信息
     * @param int $id 商品ID
     * @return array
     */
    public static function getGoodsWaring($id){
        $model = new Goods();
        $row = $model->where(['id'=>$id,'stock_warning'=>'1'])->field('branch,min_stock,max_stock')->find();
        if(empty($row)){
            return [];
        }
        if($row['branch']==1){//分仓预警
            $stock_warning = Db::name('kuyou_goods_stock_warning')->alias('gs')
                ->join('kuyou_stores s','gs.stores_id=s.id')
                ->where(['goods_id'=>$id])
                ->field('gs.stores_id,s.name,gs.min_stock,gs.max_stock')
                ->select();
            $row['warehouse'] = $stock_warning;
        }else{
            $row['warehouse'] = [];
        }
        return $row;
    }

    /**
     * 获取商品属性信息
     * @param int $id 商品ID
     * @return array
     */
    public static function getGoodsAuxiliary($id){
        $model = new Goods();
        $row = $model->where(['id'=>$id,'auxiliary'=>'1'])->field('auxiliary_type,auxiliary_type_c')->find();
        if(empty($row)){
            return [];
        }
        $auxiliary_type = unserialize($row['auxiliary_type']);
        $row['auxiliary_type'] = $auxiliary_type;

        $auxiliary_type_c = unserialize($row['auxiliary_type_c']);
        $row['auxiliary_type_c'] = $auxiliary_type_c;

        $auxiliary_ids = array_merge_recursive($auxiliary_type,$auxiliary_type_c);
        $row['auxiliary'] = $auxiliary_ids;

        $row['combination'] = self::auxiliary($auxiliary_type,$auxiliary_ids);

        $auxiliary = Db::name('kuyou_auxiliary')->where(['status'=>1])->field('name,id,pid')->select();
        foreach ($auxiliary as $auxiliary_k=>$auxiliary_v){
            if(in_array($auxiliary_v['id'],$auxiliary_ids)){
                $auxiliary[$auxiliary_k]['is_checked'] = 1;
            }else{
                $auxiliary[$auxiliary_k]['is_checked'] = 0;
            }
        }
        $tree = Tree::instance();
        $tree->init($auxiliary, 'pid');
        $auxiliary = $tree->getTreeArray(0);
        $row['auxiliary_list'] = $auxiliary;

        $auxiliary = Db::name('kuyou_auxiliary')->where(['status'=>1])->column('name','id');
        $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_id'=>$id])
            ->field('attribute_id,attr_code,barcode,unit,market_sell_price,wholesale_price,vip_price,discount,discount2,purchase')->select();
        foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
            $aux_combination = Db::name('kuyou_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_ids'] = [];
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if($aux_combination){
                $goods_attr[$goods_attr_k]['attr_id'] = $aux_combination;
                $aux_combination = explode('&',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_ids'] = $aux_combination;
                foreach ($aux_combination as $aux_combination_k=>$aux_combination_v){
                    $aux_combination[$aux_combination_k] = isset($auxiliary[$aux_combination_v])?$auxiliary[$aux_combination_v]:'';
                }
                $aux_combination = implode('/',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }
        }
        $row['auxiliary_data'] = $goods_attr;
        return $row;
    }

    /**
     * 获取商品属性组合
     * @param array $typearr 一级属性id
     * @param array $typesarr 子属性id
     * @return array
     */
    public static function auxiliary($typearr,$typesarr){
        $list = $spec_name = Db::name('kuyou_auxiliary')->order(['id'=>'desc'])->where(['id'=>['in',$typearr]])->select();
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['spec'] = Db::name('kuyou_auxiliary')->order(['id'=>'desc'])->where(['pid'=>$list_v['id'],'id'=>['in',$typesarr]])->column('name','id');
            $spec_name[$list_k]['spec'] = Db::name('kuyou_auxiliary')->order(['id'=>'desc'])->where(['pid'=>$list_v['id'],'id'=>['in',$typesarr]])->column('id');
        }
        $lists = self::combineDika($list);
        foreach ($lists as $lists_k=>$lists_v){
            $lists[$lists_k]['spec_name'] = implode('/',$lists_v['spec']);
            $lists[$lists_k]['spec_id'] = $spec_id = explode('&',$lists_v['id']);
            $lists[$lists_k]['spec_arr'] = implode('/',$spec_id);
            foreach ($spec_id as $spec_id_k=>$spec_id_v){
                $lists[$lists_k]['spec_id'][$spec_id_k] =  $spec_id_v;
            }
        }
        return $lists;
    }

    public static function combineDika(array $data) {
        $cnt = count($data);
        $result = $data[0];
        if($cnt==1){
            $list = [];
            foreach ($result['spec'] as $k=>$item) {
                $temp = [];
                $key = $k;
                $temp[] = $item;
                $list[] = ['id'=>$key,'spec'=>$temp];
            }
            return $list;
        }
        for($i = 1; $i < $cnt; $i++) {
            $result = self::combineArray($result,$data[$i]);
        }
        return $result;
    }
    public static function combineArray($arr1,$arr2) {
        $result = array();
        if(!isset($arr1['spec'])){
            $arr1['spec'] = $arr1;
        }
        foreach ($arr1['spec'] as $k1=>$item1) {
            foreach ($arr2['spec'] as $k2=>$item2) {
                $temp = [];
                if(!isset($arr1['id'])){
                    $key = $item1['id'].'&'.$k2;
                }else{
                    $key = $k1.'&'.$k2;
                }
                if(is_array($item1)){
                    foreach ($item1['spec'] as $item1_k=>$item1_v){
                        $temp[] = $item1_v;
                    }
                }else{
                    $temp[] = $item1;
                }
                $temp[] = $item2;
                $result[] = ['id'=>$key,'spec'=>$temp];
            }
        }
        return $result;
    }

    /**
     * 获取商品批次保质期信息
     * @param int $id 商品ID
     * @return array
     */
    public static function getGoodsBatch($id){
        $model = new Goods();
        $row = $model->where(['id'=>$id,'batch'=>'1'])->field('shelf_life,early_warning')->find();
        if(empty($row)){
            return [];
        }else{
            return $row;
        }
    }

    /**
     * 获取商品期初信息
     * @param int $id 商品ID
     */
    public static function getGoodsPeriod($id){
        $goods_batch = Db::name('kuyou_goods_batch')->where(['goods_id'=>$id])->select();
        $goods_stock = Db::name('kuyou_goods_period')->where(['goods_id'=>$id])
            ->field('stores_id,attribute_id,period,unit_cost,price')->select();
        foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
            foreach ($goods_batch as $goods_batch_k=>$goods_batch_v){
                if($goods_batch_v['attribute_id']==$goods_stock_v['attribute_id'] && $goods_batch_v['stores_id']==$goods_stock_v['stores_id']){
                    $goods_batch_v['manufacture'] = date('Y-m-d',$goods_batch_v['manufacture']);
                    $goods_batch_v['validity'] = date('Y-m-d',$goods_batch_v['validity']);
                    $goods_stock[$goods_stock_k]['batch_id'] = $goods_batch_v['id'];
                    $goods_stock[$goods_stock_k]['batch_name'] = $goods_batch_v['batch_name'];
                    $goods_stock[$goods_stock_k]['manufacture'] = $goods_batch_v['manufacture'];
                    $goods_stock[$goods_stock_k]['guarantee'] = $goods_batch_v['guarantee'];
                    $goods_stock[$goods_stock_k]['validity'] = $goods_batch_v['validity'];
                    $goods_stock[$goods_stock_k]['address'] = $goods_batch_v['address'];
                    $goods_stock[$goods_stock_k]['registration'] = $goods_batch_v['registration'];
                    $goods_stock[$goods_stock_k]['production'] = $goods_batch_v['production'];
                }
            }

            $stores = Db::name('kuyou_stores')
                ->where(['id'=>$goods_stock_v['stores_id']])->value('name');
            $goods_stock[$goods_stock_k]['stores_name'] = $stores;

            $goods_attr = Db::name('kuyou_goods_attr')
                ->where(['id'=>$goods_stock_v['attribute_id']])->value('attribute_id');
            $attr_ids = Db::name('kuyou_aux_combination')
                ->where(['id'=>$goods_attr])->value('attr_ids');
            $goods_stock[$goods_stock_k]['attr_ids'] = $attr_ids;
            $attr_id = explode('&',$attr_ids);
            $aux = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attr_id]])->column('name');
            sort($aux);
            $goods_stock[$goods_stock_k]['attr_name'] = implode('/',$aux);

            $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$goods_stock_v['attribute_id']])->value('id');
            $serier = Db::name('kuyou_goods_serial')
                ->where(['goods_id'=>$id,'attribute_id'=>$attribute_id,'stores_id'=>$goods_stock_v['stores_id']])
                ->field('serial,remark')->select();
            if($serier){
                $goods_stock[$goods_stock_k]['period'] = sizeof($serier);
                $goods_stock[$goods_stock_k]['serier'] = serialize($serier);
                $goods_stock[$goods_stock_k]['serierdata'] = $serier;
            }
        }
        return $goods_stock;
    }

    /**
     * 获取商品价格信息
     * @param array $data 商品
     * @return array
     */
    public static function getGoodsInfo($data){
        $model = new Goods();

        $id             = isset($data['id'])?$data['id']:'';
        $goods_code     = isset($data['goods_code'])?$data['goods_code']:'';
        $store          = isset($data['store'])?$data['store']:'';
        $attr           = isset($data['attr_id'])?$data['attr_id']:'';
        $suppliers_id  = isset($data['suppliers_id'])?$data['suppliers_id']:'';
        $customers_id  = isset($data['customers_id'])?$data['customers_id']:'';

        $type  = isset($data['type'])?$data['type']:1;//类型 1:供应商，2：客户
        $type = $type==1?1:2;
        $customers = Db::name('kuyou_customers')->where(['id'=>$customers_id])->find();
        if(empty($customers)){
            $customers['customerlevel_id'] = 1;
            //return ['status'=>500,'msg'=>'未查询到相关客户'];
        }
        switch ($customers['customerlevel_id']){
            case 1:
                $price_field = ' market_sell_price as purchase';
                break;
            case 2:
                $price_field = ' wholesale_price as purchase';
                break;
            case 3:
                $price_field = ' vip_price as purchase';
                break;
            case 4:
                $price_field = ' market_sell_price as purchase';
                break;
            case 5:
                $price_field = ' market_sell_price as purchase';
                break;
            default:
                $price_field = ' market_sell_price as purchase';
                break;
        }

        if($type==1){
            $field = 'id,goods_code,goods_name,batch as batch_status,serial as serial_status,unit_id,more_unit,more_unit_id,purchase,goods_image,inventory,note,auxiliary,manager_warehouse_id,shelf_life';
        }else{
            $field = 'id,goods_code,goods_name,batch as batch_status,serial as serial_status,unit_id,more_unit,more_unit_id,'.$price_field.',discount,discount2,goods_image,inventory,note,auxiliary,manager_warehouse_id,shelf_life';
        }
        if(!empty($id)){
            $row = $model->where(['id'=>$id])->field($field)->find();
        }else{
            $row = $model->where(['goods_code'=>$goods_code])->field($field)->find();
        }
        if(empty($row)){
            return ['status'=>500,'msg'=>'未查询到相关商品'];
        }//先查询是否有商品
        $goods_id = $row['id'];

        if(!empty($store)){
            $store_name = (new Stores())->where(['id'=>$store])->value('name');
        }else{
            $store_name = (new Stores())->where(['id'=>$row['manager_warehouse_id']])->value('name');
        }
        $row['store_name'] = $store_name;

        $basic_unit_name = (new Unit())->where(['id'=>$row['unit_id']])->value('name');
        $row['basic_unit_name'] = $basic_unit_name;

        $taxes= Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');//是否设置了税

        if($suppliers_id && $type==1){//查询供应商税率
            $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$suppliers_id])->value('vat_rate');
        }
        if(isset($suppliers) && $suppliers!==''){
            $row['taxes_rate'] = $suppliers;
        }else{
            $set= Db::name('kuyou_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
            $row['taxes_rate'] = isset($set['value'])?$set['value']:0;
        }

        $auxiliary = Db::name('kuyou_auxiliary')->where(['status'=>1])->column('name','id');
        if($type==1){
            $field = 'id,attribute_id,purchase,discount,discount2';
        }else{
            $field = 'id,attribute_id,'.$price_field.',discount,discount2';
        }
        $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_id'=>$goods_id])->field($field)->select();
        foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
            $aux_combination = Db::name('kuyou_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_ids'] = [];
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if($aux_combination){
                $goods_attr[$goods_attr_k]['attr_id'] = $aux_combination;
                $aux_combination = explode('&',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_ids'] = $aux_combination;
                foreach ($aux_combination as $aux_combination_k=>$aux_combination_v){
                    if(isset($auxiliary[$aux_combination_v])){
                        $aux_combination[$aux_combination_k] = $auxiliary[$aux_combination_v];
                    }
                }
                $aux_combination = implode('/',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }
        }


        $where = [];
        $where['goods_id'] = $goods_id;
        if($store){
            $where['stores_id'] = $store;
        }else{
            $where['stores_id'] = $row['manager_warehouse_id'];
        }
        if($attr){
            $where['attribute_id'] = $attr;
        }
        $stock = Db::name('kuyou_goods_stock')->where($where)->sum('stock');

        if($type==1){
            $field = 'id,unit,is_default,purchase,discount,discount2';
        }else{
            $field = 'id,unit,is_default,'.$price_field.',discount,discount2';
        }
        if($row['more_unit']==1){
            $unit = Db::name('kuyou_unit_conversion')->alias('uc')
                ->join('kuyou_unit u','u.id=uc.vice_unit')
                ->where(['uc.main_unit'=>$row['unit_id']])
                ->order('uc.advance_rate','ASC')
                ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                ->select();
            $unit_ids = [$row['unit_id']];
            foreach ($unit as $unit_k=>$unit_v){
                $unit_ids[] = $unit_v['id'];
            }
            $goods_price = Db::name('kuyou_goods_price')->where(['unit'=>['in',$unit_ids],'goods_id'=>$goods_id])->field($field)->select();
            foreach ($goods_price as $goods_price_k=>$goods_price_v){
                if(isset($customers['customerlevel_id']) && $customers['customerlevel_id']==4 && $goods_price_v['discount']>0){
                    $goods_price[$goods_price_k]['purchase'] = round($goods_price_v['purchase']*$goods_price_v['discount']/100,4);
                }else if(isset($customers['customerlevel_id']) && $customers['customerlevel_id']==5 && $goods_price_v['discount2']>0){
                    $goods_price[$goods_price_k]['purchase'] = round($goods_price_v['purchase']*$goods_price_v['discount2']/100,4);
                }
                foreach ($unit as $unit_k=>$unit_v){
                    if($goods_price_v['unit']==$row['unit_id']){
                        $goods_price[$goods_price_k]['advance_rate'] = 1;
                    }else if($goods_price_v['unit']==$unit_v['id']){
                        $goods_price[$goods_price_k]['advance_rate'] = $unit_v['advance_rate'];
                    }
                }
            }
        }else{
            $unit_ids = [$row['unit_id']];
        }
        $unit = Db::name('kuyou_unit')->where(['id'=>['in',$unit_ids]])->field('id,name')->select();
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($goods_price)){
                foreach ($goods_price as $goods_price_k=>$goods_price_v){
                    if($unit_v['id']==$goods_price_v['unit']){
                        $unit[$unit_k]['is_default'] = $goods_price_v['is_default'];
                        //$unit[$unit_k]['purchase'] = $goods_price_v['purchase']*$goods_price_v['advance_rate'];
                        $unit[$unit_k]['purchase'] = $goods_price_v['purchase'];
                        if($goods_price_v['is_default']!=1){
                            $unit[$unit_k]['basic_nmber'] = $goods_price_v['advance_rate'];
                        }else{
                            $unit[$unit_k]['basic_nmber'] = 1;
                        }
                    }
                }
            }else{
                if($row['auxiliary']==1 && !empty($attr)){
                    $purchase = Db::name('kuyou_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->value($price_field);
                }else{
                    $purchase = $row['purchase'];
                }
                if($unit_v['id']==$row['unit_id']){
                    $unit[$unit_k]['is_default'] = 1;
                    $unit[$unit_k]['basic_nmber'] = 1;
                    $unit[$unit_k]['purchase'] = $purchase;
                }
            }
        }

        foreach ($unit as $unit_k=>$unit_v){
            if(isset($suppliers) && $suppliers!==''){
                $tax = $suppliers;
            }else{
                $tax = $set['value'];
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1){
                $unit[$unit_k]['tax'] = 1;
                $unit[$unit_k]['tax_rate'] = $tax;
            }else{
                $unit[$unit_k]['tax'] = 0;
                $unit[$unit_k]['tax_rate'] = 0;
            }
            if(!isset($unit_v['purchase'])){
                $unit_v['purchase'] = 0;
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes==1){
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase']/(100+$tax)*100),4);
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }elseif(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes!=1){
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase']*(100+$tax)/100),4);
            }else{
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }
        }
        $data = [];
        foreach ($unit_ids as $unit_ids_k=>$unit_ids_v){
            foreach ($unit as $unit_k=>$unit_v){
                if($unit_ids_v==$unit_v['id']){
                    if(!isset($unit_v['is_default'])){
                        $unit_v['is_default'] = 2;$unit_v['basic_nmber'] = 1;
                    }
                    if($unit_v['is_default']==1){
                        $unit_v['stock'] = is_null($stock)?0:$stock;
                    }else{
                        $unit_v['stock'] = round($stock/$unit_v['basic_nmber'],2);
                    }
                    $unit_v['tax_money'] = round(($unit_v['tax_included']-$unit_v['purchase']),4);;
                    $data[] = $unit_v;
                }
            }
        }

        $row['price_data'] = $data;
        $row['attr_data'] = $goods_attr;
        return ['status'=>200,'msg'=>$row];
    }

    /**
     * 获取商品价格信息
     * @param array $data 商品
     * @return array
     */
    public static function choseGoods($data){
        $keyword       = isset($data['keyword'])?$data['keyword']:'';
        $goods_type    = isset($data['goods_type'])?$data['goods_type']:'';
        $where = [];
        if(!empty($keyword)){
            $where['goods_code|goods_name|goods_barcode'] = ['like','%'.$keyword.'%'];
        }
        if(!empty($goods_type)){
            $where['goods_type_id'] = ['in',$goods_type];
        }

        $goods = Db::name('kuyou_goods')->where($where)
            ->field('id,goods_code,goods_name,goods_barcode,goods_specification_id,goods_type_id,manager_warehouse_id,unit_id,more_unit,more_unit_id,
            market_sell_price,wholesale_price,vip_price,discount,discount2,purchase,goods_image,inventory,note,is_offten,auxiliary,batch,serial')
            ->select();
        $goods_list = [];
        $auxiliary= Db::name('kuyou_sets')->where(['name'=>'auxiliary'])->value('is_checked');
        foreach ($goods as $goods_k=>$goods_v){
            $goods_v['goods_attr'] = '';
            $goods_v['attr_code'] = '';
            $goods_v['attr_name'] = '';
            $goods_v['stock'] = $goods_v['inventory'];;
            $goods_v['number'] = '';
            $goods_list[] = $goods_v;
            if($auxiliary==1 && $goods_v['auxiliary']){
                $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_code'=>$goods_v['goods_code']])->field('id,attribute_id,attr_code')->select();
                foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
                    $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
                    if($attribute_ids){
                        $attribute_ids = explode('&',$attribute_ids);
                        $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                        $attribute_name = implode('/',$attribute);
                        $goods_v['stock'] = '';
                        $goods_v['attr_code'] = $goods_attr_v['attr_code'];
                        $goods_v['goods_attr'] = $goods_attr_v['id'];
                        $goods_v['attr_name'] = $attribute_name;
                        $goods_v['number'] = '';
                        $goods_list[] = $goods_v;
                    }
                }
            }
        }

        $page = isset($data['page'])?((int)$data['page']):1;
        $limit = isset($data['limit'])?((int)$data['limit']):10;
        $lists = $goods_list;
        if ($page>=0){
            $page = $page<=0?1:$page;
            $limit = $limit<=0?10:$limit;
            $start = ($page-1)*$limit;
            $end = ($page)*$limit;
            foreach ($goods_list as $goods_list_k=>$goods_list_v){
                if($goods_list_k<$start || $goods_list_k>=$end){
                    unset($goods_list[$goods_list_k]);
                }
            }
        }
        $list = $goods_list;
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['unit'] = ['name'=>''];
            $unit = Db::name('kuyou_unit')->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
            $list[$list_k]['unit'] = $unit;

            $type = Db::name('kuyou_goods_type')->where(['id'=>$list_v['goods_type_id']])->field('id,supplier_type_name as name')->find();
            $list[$list_k]['goods_type'] = $type;
        }
        $listarr = [];
        foreach ($list as $goods_list_k=>$goods_list_v){
            $listarr[] = $goods_list_v;
        }
        $list = $listarr;
        $result = array("count" => sizeof($lists), "list" => $list);
        return ['status'=>200,'msg'=>$result];
    }

    /**
     * 获取商品信息
     * @param array $data 商品条件
     * @return array
     */
    public static function getGoodsList($data){
        if(isset($data['goods_type']) && $data['goods_type']=='showGoodsList'){
            $prefix = config('database.prefix');
            $table = \think\Db::query("show tables like '".$prefix."kuyou_goods'");
            if(empty($table)){
                return ['status'=>500,'msg'=>'未安装进销存插件'];
            }else{
                $where = [];
                if(!empty($data['keyword'])){
                    $where['goods_code|goods_name|goods_barcode'] = ['like','%'.$data['keyword'].'%'];
                }
                if(!empty($data['goods_type_id'])){
                    $where['goods_type_id'] = ['in',$data['goods_type_id']];
                }
                if(!empty($data['goods_barcode'])){
                    $where['goods_barcode'] = ['like','%'.$data['goods_barcode'].'%'];
                }
                $where['status'] = '1';
                $page = isset($data['page'])?((int)$data['page']):1;
                $limit = isset($data['limit'])?((int)$data['limit']):10;

                $goods = Db::name('kuyou_goods')->where($where)->page($page,$limit)->select();
                $type = Db::name('kuyou_goods_type')->field('supplier_type_name as name,id')->select();
                $types = [];
                foreach ($type as $type_k=>$type_v){
                    $types[$type_v['id']] = $type_v;
                }
                $goods_list = [];
                foreach ($goods as $goods_k=>$goods_v){
                    $goods_v['goods_attr'] = '';
                    $goods_v['attr_code'] = '';
                    $goods_v['attr_name'] = '';
                    $goods_v['stock'] = $goods_v['inventory'];;
                    $goods_v['number'] = '';
                    $goods_v['goods_type'] = isset($types[$goods_v['goods_type_id']])?$types[$goods_v['goods_type_id']]:[];
                    $goods_v['goods_note'] = $goods_v['goods_specification_id'];
                    $goods_v['goods_unit'] = $goods_v['more_unit']==1?$goods_v['warehousing']:$goods_v['unit_id'];
                    $goods_v['unit_name'] = Db::name('kuyou_unit')->where(['id'=>$goods_v['goods_unit']])->value('name');
                    $goods_v['default_unit_name'] = Db::name('kuyou_unit')->where(['id'=>$goods_v['unit_id']])->value('name');

                    $data['advance_rate'] = 1;
                    if($goods_v['more_unit']==1){
                        $advance_rate = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods_v['more_unit_id'],'vice_unit'=>$goods_v['goods_unit']])->value('advance_rate');
                        if(!empty($advance_rate)){
                            $data['advance_rate'] = $advance_rate;
                        }
                    }
                    $goods_v['basic_nmber'] = $data['advance_rate'];

                    $goods_list[] = $goods_v;
                }
                $result = array("count" => sizeof($goods_list), "list" => $goods_list);
            }
        }else{
            $where = [];
            if(!empty($data['keyword'])){
                $where['goods_code|goods_name|goods_barcode'] = ['like','%'.$data['keyword'].'%'];
            }
            if(!empty($data['goods_type_id'])){
                $where['goods_type_id'] = ['in',$data['goods_type_id']];
            }
            if(!empty($data['goods_name'])){
                $where['goods_code|goods_name|goods_barcode'] = ['like','%'.$data['goods_name'].'%'];
            }
            if(!empty($data['goods_barcode'])){
                $where['goods_barcode'] = ['like','%'.$data['goods_barcode'].'%'];
            }
            if(!empty($data['goods_types'])){
                $where['goods_type'] = $data['goods_types'];
            }
            $where['status'] = '1';

            $page = isset($data['page'])?((int)$data['page']):1;
            $limit = isset($data['limit'])?((int)$data['limit']):10;

            $goods = Db::name('kuyou_goods')->where($where)->page($page,$limit)->select();
            $type = Db::name('kuyou_goods_type')->field('supplier_type_name as name,id')->select();
            $types = [];
            foreach ($type as $type_k=>$type_v){
                $types[$type_v['id']] = $type_v;
            }
            $goods_list = [];
            foreach ($goods as $goods_k=>$goods_v){
                $goods_v['goods_attr'] = '';
                $goods_v['attr_code'] = '';
                $goods_v['attr_name'] = '';
                $goods_v['stock'] = $goods_v['inventory'];
                $goods_v['number'] = '';
                $goods_v['goods_type'] = isset($types[$goods_v['goods_type_id']])?$types[$goods_v['goods_type_id']]:[];
                $goods_v['goods_note'] = $goods_v['goods_specification_id'];
                $goods_v['goods_unit'] = $goods_v['more_unit']==1?$goods_v['warehousing']:$goods_v['unit_id'];
                $goods_v['unit_name'] = Db::name('kuyou_unit')->where(['id'=>$goods_v['goods_unit']])->value('name');
                $goods_v['default_unit_name'] = Db::name('kuyou_unit')->where(['id'=>$goods_v['unit_id']])->value('name');
                $data['advance_rate'] = 1;
                if($goods_v['more_unit']==1){
                    $advance_rate = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods_v['more_unit_id'],'vice_unit'=>$goods_v['goods_unit']])->value('advance_rate');
                    if(!empty($advance_rate)){
                        $data['advance_rate'] = $advance_rate;
                    }
                }
                $goods_v['basic_nmber'] = $data['advance_rate'];

                $goods_list[] = $goods_v;
            }
            $result = array("count" => sizeof($goods_list), "list" => $goods_list);
        }
        return ['status'=>200,'msg'=>$result];
    }
}
